package com.hoas.databox.spring;

import com.hoas.databox.redis.RedisDataRepostroy;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.Protocol;
import redis.clients.util.SafeEncoder;

/**
 * Redis寄存方式，结合spring方式
 */
public class SpringRedisDataRepostroy extends RedisDataRepostroy {

    private RedisTemplate redisTemplate;

    public SpringRedisDataRepostroy(String keyPrefix, RedisTemplate redisTemplate) {
        super(keyPrefix, null);
        this.redisTemplate = redisTemplate;
    }

    public SpringRedisDataRepostroy(RedisTemplate redisTemplate) {
        super(null);
        this.redisTemplate = redisTemplate;
    }

    protected boolean setIfAbsent(final String key, final String value, final long exptime) {
        Boolean b = (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {

            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
                RedisSerializer keySerializer = redisTemplate.getKeySerializer();
                Object obj = connection.execute("set", keySerializer.serialize(key),
                        valueSerializer.serialize(value),
                        SafeEncoder.encode("NX"),
                        SafeEncoder.encode("EX"),
                        Protocol.toByteArray(exptime));
                return obj != null;
            }
        });
        return b;
    }

    @Override
    protected String getRedis(String key) {
        return (String) redisTemplate.opsForValue().get( key );
    }
}
